package code;

import interfaces.*;
import java.util.*;

public class OrderListImpl implements OrderList{
	private LinkedList<Order> orders = new LinkedList<Order>();
	
	public OrderListImpl(){
	}
	
	public void addOrder(Order order){
		orders.add(order);
	}
	
	public void completeOrder(Order order){
		orders.remove(order);
	}
	
	public void completeOrder(int order){
		Order rem = null;
		for(Order o : orders){
			if (o.getId() == order){
				if (rem == null)
					rem = o;
				else {
					// TODO make error report for multiple order-ID!
				}
			}
		}
		if (rem != null){
			orders.remove(rem);
		}
	}
	
	public Order getNextOrder(){
		return orders.get(0);
	}
	
	public void changePriority(Order o, int newPos){
		int oldPos = orders.indexOf(o);
		if (oldPos <= newPos){
			while(oldPos < newPos){
				Order tempOrder = orders.get(oldPos);
				orders.set(oldPos, orders.get(oldPos + 1));
				orders.set(oldPos + 1, tempOrder);
				oldPos++;
			}
		} else {
			while(oldPos > newPos){
				Order tempOrder = orders.get(oldPos);
				orders.set(oldPos, orders.get(oldPos - 1));
				orders.set(oldPos - 1, tempOrder);
				oldPos--;
			}
		}
	}
	
	public Order getItem(int item){
		if (item < orders.size()){
			return orders.get(item);
		} else {
			throw new NullPointerException("index out of bounds.");
		}
	}
	
	public void sortByDate(){
		for(int i = 0; i < orders.size(); i++){
			for(int j = 0; j < orders.size() - 1; j++){
				if(orders.get(j).getDelivery().after(orders.get(j+1).getDelivery())){
					Order o = orders.get(j);
					orders.set(j, orders.get(j+1));
					orders.set(j+1, o);
				}
			}
		}
	}
}